import 'package:flutter/material.dart';

/// 简易的列表创建
Widget buildSampleList(List<Widget> list) {
  return GridView(
    scrollDirection: Axis.horizontal,
    // 滚动方向
    reverse: false,
    // gridDelegate 控制子控件的排列
    gridDelegate:
        // 交叉轴方向上固定数量，对
        // 于垂直方向的GridView 来说交叉轴方向指的是水平方向
        buildSampleSliverGridDelegate(),
    // 交叉轴方向上尽量大，比如
    // 水平方上有500 空间，指定此值为150，那么可以放3 个，剩余一些空间，
    // 此时GridView 将会缩小每一个Item，放置4
    //  SliverGridDelegateWithMaxCrossAxisExtent(3),
    children: list,
    padding: EdgeInsets.all(6),
  );
}

// 构建gridDelegate
SliverGridDelegateWithFixedCrossAxisCount buildSampleSliverGridDelegate() {
  return SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 3, // ：交叉轴方向上个数
      crossAxisSpacing: 2, // 交叉轴方向上之间的间隔
      mainAxisSpacing: 4, // 主轴方向上2 行之间的间隔
      childAspectRatio: 16 / 9 // 4/3:4:3,16:9: 16/9
      );
}

/// 动态数据创建
Widget buildSampleGridListBuilder(List<Widget> list) {
  return GridView.builder(
    scrollDirection: Axis.horizontal,
    reverse: false,
    gridDelegate: buildSampleSliverGridDelegate(),
    itemBuilder: (context, index) {
      return list[index % list.length];
    },
    padding: EdgeInsets.all(6),
    itemCount: 100,
  );
}

/// 使用GridView.custom构建
Widget buildSampleCustom(List<Widget> list) {
  return GridView.custom(
      padding: EdgeInsets.all(6),
      gridDelegate: buildSampleSliverGridDelegate(),
      childrenDelegate: SliverChildBuilderDelegate((context, index) {
        return list[index % list.length];
      }, childCount: 50));
}

/// 使用GridView.count创建
Widget buildSampleCount(List<Widget> list) {
  return GridView.count(
      crossAxisCount: 3,
      crossAxisSpacing: 4,
      mainAxisSpacing: 4,
      padding: EdgeInsets.all(6),
      children: buildGridItemViewByDynamic(list));
}

/// 生成列表
List<Widget> buildGridItemViewByDynamic(List<Widget> list) {
  return List.generate(50, (index) {
    if (list.isEmpty) {
      return Container();
    }

    return list[index % list.length];
  });
}

/// 基于GridView.extent创建列表
Widget buildSampleExtent(List<Widget> list) {
  return GridView.extent(
    crossAxisSpacing: 4,
    mainAxisSpacing: 4,
    maxCrossAxisExtent: 100,
    padding: EdgeInsets.all(6),
    children: buildGridItemViewByDynamic(list),
  );
}
